﻿Imports WiremetModel.Entities.OEM

Public Class NormaInputDialog

    Private _unitOfWork As UnitOfWork


    Private _norma As Norma
    Public Property Norma() As Norma
        Get
            Return _norma
        End Get
        Private Set(ByVal value As Norma)
            _norma = value
        End Set
    End Property


    Public Sub New()
        InitializeComponent()
        _unitOfWork = New UnitOfWork()
        Norma = New Norma()
    End Sub


    Public Sub New(ByVal norma As Norma)
        Me.New()
        tb_NormaNazwa.Text = norma.Nazwa
        _norma = norma
    End Sub

    Private Sub NormaInputDialog_FormClosed(ByVal sender As Object, ByVal e As FormClosedEventArgs) Handles Me.FormClosed
        _unitOfWork.Dispose()
    End Sub

    Public Function IsNormaNazwaValid(ByVal nazwa As String) As Boolean
        Return Not String.IsNullOrEmpty(nazwa)
    End Function

    Public Function IsNormaNazwaUnique(ByVal nazwa As String) As Boolean
        Dim normaRepository As New Repository(Of Norma)(_unitOfWork)
        Return Not normaRepository.GetAll().Where(Function(x) x.Nazwa = nazwa AndAlso (IsNothing(Norma) OrElse x.Id <> Norma.Id)).Any()
    End Function

    Private Sub btn_NormaZatwierdź_Click(sender As System.Object, e As System.EventArgs) Handles btn_Accept.Click
        Try
            Dim normaNazwa As String = tb_NormaNazwa.Text.Trim()

            If Not IsNormaNazwaValid(normaNazwa) Then
                Throw New Exception("Podana nazwa jest nieprawidłowa.")
            End If

            If Not IsNormaNazwaUnique(normaNazwa) Then
                Throw New Exception("Istnieje już norma o takiej nazwie." & vbNewLine &
                                    "Podana nazwa musi być unikalna.")
            End If

            Dim confirmationDialogResult As DialogResult = MessageBox.Show("Czy jesteś pewień?", "Uwaga!", MessageBoxButtons.YesNo, MessageBoxIcon.Warning)
            If confirmationDialogResult = Windows.Forms.DialogResult.Yes Then

                Norma.Nazwa = normaNazwa

                DialogResult = Windows.Forms.DialogResult.OK
            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning)
        End Try
    End Sub

    Private Sub btn_Anuluj_Click(sender As System.Object, e As System.EventArgs) Handles btn_Cancel.Click
        DialogResult = Windows.Forms.DialogResult.Cancel
    End Sub
End Class